﻿using Common.Property;
using Common.Utility;
using Dapper;
using DapperExtensions;
using Domain.Sys;
using Infrastructure.Dapper;
using IRepository.Sys;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repository.Sys
{
    public class UserRoleRepository : RepositoryBase<UserRole>, IUserRoleRepository
    {
        public async Task<bool> UpdateRoles(string userid, List<UserRole> roles, OperatorInfo op)
        {
            using (IDbConnection conn = ConnectionFactory.CreateSqlConnection())
            {
                var transection = conn.BeginTransaction();
                try
                {
                    var delSql = @"DELETE UserRole WHERE UserId = @UserId";
                    await conn.ExecuteAsync(delSql, new { UserId = userid }, transection);

                    foreach (var role in roles)
                    {
                        role.IsDelete = 0;
                        role.CreateUserId = op.UserId;
                        role.CreateTime = DateTime.Now;
                        role.UpdateUserId = op.UserId;
                        role.UpdateTime = DateTime.Now;
                        var result = await conn.InsertAsync<UserRole>(role, transection);
                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.Info("InsertAsync UserRole False");
                            transection.Rollback();
                            return false;
                        }
                    }
                    transection.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    transection.Rollback();
                    return false;
                }
            }
        }

        public async Task<List<UserRole>> GetRoleByUserId(string userid)
        {
            var sql = @"SELECT Id, UserId, RoleId
                      FROM UserRole
                      WHERE UserId = @UserId";

            using (IDbConnection conn = ConnectionFactory.CreateSqlConnection())
            {
                var result = await conn.QueryAsync<UserRole>(sql, new { UserId = userid });
                return result.ToList();
            }
        }
    }
}
